package org.example.demo.service;

import org.springframework.stereotype.Service;
import org.springframework.scheduling.annotation.Scheduled;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.math.BigInteger;
import java.time.Instant;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.Collections;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

/**
 * 商品转移时间本地存储服务
 * 用于在本地保存商品所有权转移的时间记录
 */
@Service
public class TransferTimeService {
    
    // 内部类，用于存储转移记录
    public static class TransferRecord implements Serializable {
        private static final long serialVersionUID = 1L;
        private String goodsId;
        private List<String> owners;
        private List<Long> timestamps;
        
        public TransferRecord(String goodsId) {
            this.goodsId = goodsId;
            this.owners = new ArrayList<>();
            this.timestamps = new ArrayList<>();
        }
        
        public void addTransfer(String owner, Long timestamp) {
            this.owners.add(owner);
            this.timestamps.add(timestamp);
        }
        
        public List<String> getOwners() {
            return owners;
        }
        
        public List<Long> getTimestamps() {
            return timestamps;
        }
        
        public String getGoodsId() {
            return goodsId;
        }
    }
    
    // 存储所有商品的转移记录
    private Map<String, TransferRecord> transferRecords = new ConcurrentHashMap<>();
    
    // 数据文件路径
    private final String DATA_FILE;
    
    /**
     * 构造函数，初始化数据文件路径
     */
    public TransferTimeService() {
        // 使用固定路径，确保数据文件存储在稳定的位置
        String userHome = System.getProperty("user.home");
        DATA_FILE = userHome + File.separator + "blockchain_goods_transfer_records.dat";
        System.out.println("转移记录数据文件路径: " + DATA_FILE);
    }
    
    /**
     * 服务启动时加载数据
     */
    @PostConstruct
    public void init() {
        loadData();
    }
    
    /**
     * 服务关闭前保存数据
     */
    @PreDestroy
    public void destroy() {
        try {
            System.out.println("应用关闭，保存转移记录数据...");
            saveData();
            System.out.println("转移记录数据保存完成");
        } catch (Exception e) {
            System.err.println("应用关闭时保存数据失败: " + e.getMessage());
        }
    }
    
    /**
     * 定时保存数据（每10分钟）
     */
    @Scheduled(fixedRate = 600000)
    public void scheduledSave() {
        saveData();
    }
    
    /**
     * 从文件加载数据
     */
    @SuppressWarnings("unchecked")
    private void loadData() {
        File file = new File(DATA_FILE);
        if (file.exists()) {
            try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
                transferRecords = (Map<String, TransferRecord>) ois.readObject();
                System.out.println("成功加载转移记录数据: " + transferRecords.size() + " 条记录");
            } catch (Exception e) {
                System.err.println("加载转移记录数据失败: " + e.getMessage());
                transferRecords = new ConcurrentHashMap<>();
            }
        } else {
            System.out.println("转移记录数据文件不存在，将使用空记录初始化");
            transferRecords = new ConcurrentHashMap<>();
        }
    }
    
    /**
     * 手动触发保存数据
     */
    public void triggerSave() {
        saveData();
    }
    
    /**
     * 保存数据到文件，同时创建备份
     */
    private void saveData() {
        try {
            // 确保父目录存在
            File file = new File(DATA_FILE);
            File parentDir = file.getParentFile();
            if (parentDir != null && !parentDir.exists()) {
                parentDir.mkdirs();
            }
            
            // 创建备份文件
            File backupFile = new File(DATA_FILE + ".bak");
            if (file.exists()) {
                try {
                    Files.copy(file.toPath(), backupFile.toPath(), 
                               StandardCopyOption.REPLACE_EXISTING);
                    System.out.println("已创建备份文件: " + backupFile.getAbsolutePath());
                } catch (IOException e) {
                    System.err.println("创建备份文件失败: " + e.getMessage());
                }
            }
            
            // 保存数据
            try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) {
                oos.writeObject(transferRecords);
                System.out.println("成功保存转移记录数据: " + transferRecords.size() + " 条记录到 " + file.getAbsolutePath());
            }
        } catch (Exception e) {
            System.err.println("保存转移记录数据失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 记录商品的初始所有者
     */
    public void recordInitialOwner(String goodsId, String owner) {
        TransferRecord record = transferRecords.computeIfAbsent(
            goodsId, id -> new TransferRecord(id)
        );
        
        // 记录初始所有者和时间
        record.addTransfer(owner, Instant.now().getEpochSecond());
    }
    
    /**
     * 记录商品所有权转移
     */
    public void recordTransfer(String goodsId, String newOwner) {
        TransferRecord record = transferRecords.computeIfAbsent(
            goodsId, id -> new TransferRecord(id)
        );
        
        // 记录新所有者和转移时间
        record.addTransfer(newOwner, Instant.now().getEpochSecond());
    }
    
    /**
     * 获取指定商品的所有权转移记录
     */
    public TransferRecord getTransferRecord(String goodsId) {
        return transferRecords.get(goodsId);
    }
    
    /**
     * 获取商品的所有权转移时间列表
     */
    public List<Long> getTransferTimestamps(String goodsId) {
        TransferRecord record = transferRecords.get(goodsId);
        if (record != null) {
            return record.getTimestamps();
        }
        return Collections.emptyList();
    }
    
    /**
     * 获取商品的历史所有者列表
     */
    public List<String> getHistoryOwners(String goodsId) {
        TransferRecord record = transferRecords.get(goodsId);
        if (record != null) {
            return record.getOwners();
        }
        return Collections.emptyList();
    }
    
    /**
     * 删除商品记录
     */
    public void removeRecord(String goodsId) {
        transferRecords.remove(goodsId);
    }
    
    /**
     * 清除所有商品转移记录
     * 在商品ID重置或其他需要清空所有记录的情况下使用
     */
    public void clearAllRecords() {
        transferRecords.clear();
        System.out.println("已清空所有商品转移记录");
        
        // 清空后立即保存，确保数据文件也被清空
        saveData();
    }
    
    /**
     * 保存转移记录
     */
    public void saveTransferRecord(String goodsId, TransferRecord record) {
        transferRecords.put(goodsId, record);
        System.out.println("保存商品 " + goodsId + " 的转移记录，共 " + record.getTimestamps().size() + " 条时间戳");
    }
} 